package main

import (
	"flag"
	"gitee.com/baal1990/epidemic/core"
	"gitee.com/baal1990/epidemic/global"
	"gitee.com/baal1990/epidemic/initialize"
	"gitee.com/baal1990/epidemic/model/epidemic"
	epidemic2 "gitee.com/baal1990/epidemic/service/epidemic"
	"github.com/xuri/excelize/v2"
	"go.uber.org/zap"
	"strings"
	"time"
)

var (
	Type = ""
	File = ""
)

//1、删除涉疫人员管理中已返岗
//2、truncate history
//3、导入人力表
//4、导入重点人群表

func main() {
	flag.StringVar(&Type, "type", "", "related_staff/related_staff_history/check")
	flag.StringVar(&File, "file", "", "")
	var privateKeyFile = flag.String("private_key_file", "private.key", "private key file")
	var publicKeyFile = flag.String("public_key_file", "public.key", "private key file")
	flag.Parse()
	global.GVA_VP = core.Viper() // 初始化Viper
	global.GVA_LOG = core.Zap()  // 初始化zap日志库
	zap.ReplaceGlobals(global.GVA_LOG)
	global.GVA_DB = initialize.Gorm()                      // gorm连接数据库
	initialize.InitCrypto(*privateKeyFile, *publicKeyFile) // 初始化加密
	switch Type {
	case "related_staff":
		ImportRelatedStaff()
	case "related_staff_history":
		ImportRelatedStaffHistory()
	case "check":
		CheckUser()
	default:
		global.GVA_LOG.Sugar().Info("invalid type")
	}
}

type StaffInfo struct {
	Mobile                   string
	Organization             string
	ResidentialAddressCode   string
	ResidentialAddressName   string
	ResidentialAddressDetail string
}

func CheckUser() {
	var affects int
	// 获取信息
	file, err := excelize.OpenFile(File)
	if err != nil {
		global.GVA_LOG.Sugar().Error("CheckUser open file, err=", err)
		return
	}
	defer file.Close()
	// 创建db
	//db := global.GVA_DB.Model(&epidemic.EpidemicRelatedStaff{})
	sheets := file.GetSheetList()
	if len(sheets) == 0 {
		global.GVA_LOG.Sugar().Error("CheckUser empty file")
		return
	}
	rows, err := file.GetRows(sheets[0])
	if err != nil {
		global.GVA_LOG.Sugar().Error("CheckUser GetRows fail, err=", err)
		return
	}
	for i, row := range rows {
		if i != 0 {
			var staff epidemic.EpidemicRelatedStaff
			departmentKey, _ := epidemic2.GetValueByKeyAndName("department", row[1])
			staff.Name = row[0]
			staff.Department = departmentKey
			info := StaffInfo{}
			db2 := global.GVA_DB.Table("epidemic_user")
			if err = db2.Where("AES_DECRYPT(FROM_BASE64(`name`),'"+global.ENCRYPTKEY_AES+"')=? and department=? ", staff.Name, staff.Department).
				Select("mobile,organization,residential_address_code,residential_address_name,residential_address_detail").
				Find(&info).Error; err != nil {
				global.GVA_LOG.Sugar().Info("CheckUser no such user", row[1], staff.Name)
			}
			if info.Mobile == "" {
				global.GVA_LOG.Sugar().Info("CheckUser no such user", row[1], ",", staff.Name)
			}
		}
	}
	//if err = db.Table("epidemic_related_staff").Save(list).Error; err != nil {
	//	global.GVA_LOG.Sugar().Error("ImportRelatedStaff Save fail, err=", err)
	//	return
	//}
	global.GVA_LOG.Sugar().Info("ImportRelatedStaff import ", affects, " records")
}

func ImportRelatedStaff() {
	var affects int
	// Sync first
	Sync()
	// 获取信息
	file, err := excelize.OpenFile(File)
	if err != nil {
		global.GVA_LOG.Sugar().Error("ImportRelatedStaff open file, err=", err)
		return
	}
	defer file.Close()
	// 创建db
	sheets := file.GetSheetList()
	if len(sheets) == 0 {
		global.GVA_LOG.Sugar().Error("ImportRelatedStaff empty file")
		return
	}
	rows, err := file.GetRows(sheets[0])
	if err != nil {
		global.GVA_LOG.Sugar().Error("ImportRelatedStaff GetRows fail, err=", err)
		return
	}
	for i, row := range rows {
		if i != 0 && len(row) > 0 {
			if len(row) > 2 && row[1] == "" {
				continue
			}
			departmentKey, _ := epidemic2.GetValueByKeyAndName("department", row[2])
			workcityKey, _ := epidemic2.GetValueByKeyAndName("workcity", row[4])
			typeKey, _ := epidemic2.GetValueByKeyAndName("investigation_type", row[5])
			appletKey, _ := epidemic2.GetValueByKeyAndName("investigation_isupload", row[3])
			info := epidemic.EpidemicUser{}
			db2 := global.GVA_DB.Table("epidemic_user")
			if err = db2.Where("AES_DECRYPT(FROM_BASE64(`name`),'"+global.ENCRYPTKEY_AES+"')=? and department=? ", row[1], departmentKey).
				Find(&info).Error; err != nil {
				global.GVA_LOG.Sugar().Error("ImportRelatedStaff no such user", row[2], row[1])
				return
			}
			if info.Mobile == "" {
				global.GVA_LOG.Sugar().Warn("ImportRelatedStaff no such user", row[2], ",", row[1])
			}
			// 如果系统已有，更新字段
			service := epidemic2.EpidemicRelatedStaffService{}
			staff, err := service.GetEpidemicRelatedStaffInfoUserSide(info.Mobile)
			if err != nil {
				global.GVA_LOG.Sugar().Info("ImportRelatedStaff no such staff", row[2], ",", row[1])
			}
			staff.Mobile = info.Mobile
			staff.Name = row[1]
			staff.Company = "1"
			staff.Department = departmentKey
			staff.Organization = info.Organization
			staff.Location = workcityKey
			staff.AppletReport = appletKey
			staff.IsolationType = typeKey
			staff.Region = info.ResidentialAddressCode
			staff.RegionName = info.ResidentialAddressName
			staff.ResidentialAddress = info.ResidentialAddressDetail
			content := strings.Split(row[6], "\n")
			for _, e := range content {
				if strings.HasPrefix(e, "所属社区：") {
					tmp := strings.Split(e, "：")
					staff.Community = tmp[1]
				} else if strings.HasPrefix(e, "社区电话：") {
					tmp := strings.Split(e, "：")
					staff.CommunityTel = tmp[1]
				} else if strings.HasPrefix(e, "情况描述：") {
					tmp := strings.Split(e, "：")
					staff.Description = tmp[1]
				} else if strings.HasPrefix(e, "社区要求：") {
					tmp := strings.Split(e, "：")
					staff.CommunityRequirements = tmp[1]
				} else if strings.HasPrefix(e, "所属街道：") {
					tmp := strings.Split(e, "：")
					staff.Street = tmp[1]
				}
			}
			if row[7] != "" {
				t, _ := time.ParseInLocation("2006/1/2", row[7], time.Local)
				staff.HomeBeginDate = &t
			}
			if row[8] != "" {
				t, _ := time.ParseInLocation("2006/1/2", row[8], time.Local)
				staff.ReturnDate = &t
			}
			if row[9] != "" {
				t, _ := time.ParseInLocation("2006/1/2", row[9], time.Local)
				staff.CompanyOaDate = &t
			}
			if row[10] != "" {
				t, _ := time.ParseInLocation("2006/1/2", row[10], time.Local)
				staff.ReportDate = &t
			}
			if len(row) == 12 {
				staff.ReportedBy = row[11]
			}
			if err = service.SaveEpidemicRelatedStaffForImport(staff); err != nil {
				global.GVA_LOG.Sugar().Error("ImportRelatedStaff save fail, mobile=[", staff.Mobile, "], err=[", err, "]")
				return
			}
			// 查询id
			tmp, err := service.GetEpidemicRelatedStaffInfoUserSide(staff.Mobile)
			if err != nil {
				global.GVA_LOG.Sugar().Error("ImportRelatedStaff get fail, mobile=[", staff.Mobile, "], err=[", err, "]")
				return
			}
			// 同步history
			service2 := epidemic2.EpidemicRelatedStaffHistoryService{}
			var count int64
			db3 := global.GVA_DB.Model(&epidemic.EpidemicRelatedStaffHistory{})
			db3 = db3.Table("epidemic_related_staff_history")
			if err = db3.Where("related_id=?", tmp.ID).
				Count(&count).Error; err != nil {
				global.GVA_LOG.Sugar().Error("ImportRelatedStaff fail, mobile=[", staff.Mobile, "], err=[", err, "]")
				return
			}
			mode := global.SYNC_MODE_ADD
			if count != 0 {
				mode = global.SYNC_MODE_UPDATE
			}
			service2.SyncHistory(staff.Mobile, mode)
			affects++
		}
	}
	global.GVA_LOG.Sugar().Info("ImportRelatedStaff import ", affects, " records")
}

func ImportRelatedStaffHistory() {
	var affects int
	// 获取信息
	file, err := excelize.OpenFile(File)
	if err != nil {
		global.GVA_LOG.Sugar().Error("ImportRelatedStaffHistory open file, err=", err)
		return
	}
	defer file.Close()
	// 创建db
	db := global.GVA_DB.Model(&epidemic.EpidemicRelatedStaffHistory{})
	sheets := file.GetSheetList()
	if len(sheets) == 0 {
		global.GVA_LOG.Sugar().Error("ImportRelatedStaffHistory empty file")
		return
	}
	rows, err := file.GetRows(sheets[0])
	if err != nil {
		global.GVA_LOG.Sugar().Error("ImportRelatedStaffHistory GetRows fail, err=", err)
		return
	}
	var histList []epidemic.EpidemicRelatedStaffHistory
	for i, row := range rows {
		if i != 0 {
			var hist epidemic.EpidemicRelatedStaffHistory
			//id, _ := strconv.Atoi(row[0])
			departmentKey, _ := epidemic2.GetValueByKeyAndName("department", row[2])
			workcityKey, _ := epidemic2.GetValueByKeyAndName("workcity", row[3])
			typeKey, _ := epidemic2.GetValueByKeyAndName("investigation_type", row[4])
			//hist.Id = uint(id)
			hist.Name = row[1]
			hist.Company = "1"
			hist.Department = departmentKey
			hist.Location = workcityKey
			hist.IsolationType = typeKey
			hist.Details = row[5]
			hist.CreatedAt = time.Now()
			if row[6] != "" {
				t, _ := time.ParseInLocation("2006/1/2", row[6], time.Local)
				hist.HomeBeginDate = &t
			}
			if len(row) == 8 && row[7] != "" {
				t, _ := time.ParseInLocation("2006/1/2", row[7], time.Local)
				hist.ReturnDate = &t
			}

			db2 := global.GVA_DB.Table("epidemic_user")
			if err = db2.Where("AES_DECRYPT(FROM_BASE64(`name`),'"+global.ENCRYPTKEY_AES+"')=? and department=? and company=?", hist.Name, hist.Department, hist.Company).
				Select("mobile").
				Find(&hist.Mobile).Error; err != nil {
				global.GVA_LOG.Sugar().Warn("ImportRelatedStaffHistory no such user", row[2], row[3], hist.Name)
			}
			histList = append(histList, hist)
			affects++
		}
	}
	if err = db.Table("epidemic_related_staff_history").Save(histList).Error; err != nil {
		global.GVA_LOG.Sugar().Error("ImportRelatedStaffHistory Save fail, err=", err)
		return
	}
	global.GVA_LOG.Sugar().Info("ImportRelatedStaffHistory import ", affects, " records")
}

func Sync() {
	service := epidemic2.EpidemicRelatedStaffService{}
	staffList, err := service.GetEpidemicRelatedStaffInfoListForImport()
	if err != nil {
		global.GVA_LOG.Sugar().Error("Sync find fail, err=", err)
		return
	}
	service2 := epidemic2.EpidemicRelatedStaffHistoryService{}
	for _, staff := range staffList {
		var count int64
		db3 := global.GVA_DB.Model(&epidemic.EpidemicRelatedStaffHistory{})
		db3 = db3.Table("epidemic_related_staff_history")
		if err = db3.Where("mobile=? and return_date is null", staff.Mobile).
			Count(&count).Error; err != nil {
			global.GVA_LOG.Sugar().Error("ImportRelatedStaff fail, mobile=[", staff.Mobile, "], err=[", err, "]")
			return
		}
		service2.SyncHistory(staff.Mobile, global.SYNC_MODE_ADD)
	}
}
